package com.example.orderfood2.viewAllInformation;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.R;
import com.example.orderfood2.Repository.ClassInfoRepository;
import com.example.orderfood2.Repository.StudentRepository;
import com.example.orderfood2.TeacherActivity;
import com.example.orderfood2.entity.Student;
import com.example.orderfood2.util.DBUtil;

import java.util.List;
import java.util.Locale;

import javax.xml.transform.Source;

public class EditStudentActivity extends AppCompatActivity {

    private StudentRepository dbUtil;
    private ClassInfoRepository dbUtil1;
    private int Id;
    // 声明UI组件
    private EditText etUsername, etPassword, etScore, etScience;
    private RadioGroup radioSex;
    private Spinner spinnerClass;
    private TextView tvBirthDate, tvEnrolDate;
    private Button btnSubmit;
    private String selectedBirthDate, selectedEnrolDate;
    private String Source; // 成员变量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        dbUtil= DatabaseManager.getInstance(this).getStudentRepository();
        dbUtil1= DatabaseManager.getInstance(this).getClassInfoRepository();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_edit_student);
        // 初始化数据库
//        dbUtil = new DBUtil(this);
        // 获取传递过来的ID和Source
        Id = getIntent().getIntExtra("id", -1);
        Source=getIntent().getStringExtra("source");
        if(Id==-1){
            Toast.makeText(this, "无效的班级ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        // 初始化视图,获取各个组件
        initViews();
        // 加载班级数据
        loadClassData();
        btnSubmit.setOnClickListener(v-> {
            updateStudentInfo();
            Intent intent;
            if("ViewAllStudentInformationActivity".equals(Source)){
                intent=new Intent(EditStudentActivity.this,ViewAllStudentInformationActivity.class);
            }else {
                intent=new Intent(EditStudentActivity.this, TeacherActivity.class);
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        });
    }
    private void initViews(){
        etUsername = findViewById(R.id.et_update_username);
        etPassword = findViewById(R.id.et_update_password);
        etScore = findViewById(R.id.et_update_user_score);
        radioSex = findViewById(R.id.update_user_sex);
        spinnerClass = findViewById(R.id.spinner_update_user_class_id);
        tvBirthDate = findViewById(R.id.update_user_date);
        tvEnrolDate = findViewById(R.id.update_user_enrol);
        btnSubmit = findViewById(R.id.update_user_submit);
        // 设置日期选择监听
        findViewById(R.id.update_user_date_picker).setOnClickListener(v -> showBirthDatePicker());
        findViewById(R.id.update_user_date_enrol).setOnClickListener(v -> showEnrolDatePicker());
    }
    private void loadClassData(){
        // 1. 加载学生信息
        Student student = dbUtil.getStudentById(Id);
        if (student == null) {
            Toast.makeText(this, "学生信息加载失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        // 2. 填充基本信息
        etUsername.setText(student.getUsername());
        etPassword.setText(student.getPassword());
        etScore.setText(student.getScore());
// 设置性别
        if ("女".equals(student.getSex())) {
            RadioButton femaleRadioButton = findViewById(R.id.update_user_female);
            femaleRadioButton.setChecked(true);
        } else {
            RadioButton maleRadioButton = findViewById(R.id.update_user_male);
            maleRadioButton.setChecked(true);
        }
        // 4. 设置日期
        tvBirthDate.setText(student.getDate());
        selectedBirthDate = student.getDate();
        tvEnrolDate.setText(student.getEnrol());
        selectedEnrolDate = student.getEnrol();
        // 5. 加载班级列表
        loadClassSpinner(student.getClassId());
    }
    private void loadClassSpinner(String currentClassId){
        // 从数据库获取班级列表
        List<String> classes = dbUtil1.QueryClassInfo();
        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                classes
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerClass.setAdapter(adapter);
        // 设置默认选中项
        int position = classes.indexOf(currentClassId);
        if (position >= 0) {
            spinnerClass.setSelection(position);
        }
    }
    private void showBirthDatePicker() {
        showDatePicker(selectedBirthDate, date -> {
            selectedBirthDate = date;
            tvBirthDate.setText(date);
        });
    }
//    private void showBirthDatePicker() {
//        showDatePicker(selectedBirthDate, new DateSelectListener() {
//            @Override
//            public void onDateSelected(String date) {
//                selectedBirthDate = date; // 更新存储的日期
//                tvBirthDate.setText(date); // 更新 UI
//            }
//        });
//    }
    private void showEnrolDatePicker() {
        showDatePicker(selectedEnrolDate, date -> {
            selectedEnrolDate = date;
            tvEnrolDate.setText(date);
        });
    }
    private void showDatePicker(String initialDate,DateSelectListener listener){
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(
                this,
                (view, year, month, day) -> {
                    String selectedDate = String.format(Locale.getDefault(),
                            "%d-%02d-%02d", year, month + 1, day);
                    //触发接口，具体操作在141和142行
                    listener.onDateSelected(selectedDate);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        dialog.show();
    }
    interface DateSelectListener {
        void onDateSelected(String date);
    }
    private void updateStudentInfo(){
        // 1. 收集数据
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String score = etScore.getText().toString().trim();
        String sex = ((RadioButton) findViewById(radioSex.getCheckedRadioButtonId())).getText().toString();
        String classId = (String) spinnerClass.getSelectedItem();
// 2. 验证数据
        if (username.isEmpty() || password.isEmpty() || score.isEmpty()
                || selectedBirthDate == null || selectedEnrolDate == null) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }
// 3. 更新数据库
        Student student = new Student(
                null,
                username,
                password,
                sex,
                classId,
                score,
                selectedBirthDate,
                selectedEnrolDate
        );
        if (dbUtil.updateStudent(Id, student)) {
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }
    }
}